package service

import (
	"cr.org/constant"
	"cr.org/model"
	"cr.org/modules/repository"
	"cr.org/utils"
	"fmt"
	"time"
)

type userService struct {
	baseService
}

// UserLogin 用户登录，返回token
func (ser userService) UserLogin(loginAccount model.LoginAccount) (result model.LoginSuccess, base utils.BaseClaims, err error) {
	var (
		user         *model.User
		rs           []string
		accessToken  string
		refreshToken string
	)
	user, err = repository.UserRepository.FindUserByAccount(loginAccount.Username)
	if err != nil {
		return
	}
	if user.Password != loginAccount.Password {
		return result, base, fmt.Errorf("密码错误: %v ", loginAccount)
	}
	j := utils.NewJWT()
	base = utils.BaseClaims{
		UserID:    user.UserId,
		Username:  user.Username,
		AccountLv: user.AccountLv,
	}
	accessToken, err = j.CreateToken(base, constant.JWTAccessTime)
	refreshToken, err = j.CreateToken(base, constant.JWTRefreshTime)
	result = model.LoginSuccess{
		Roles:        rs,
		AccessToken:  accessToken,
		RefreshToken: refreshToken,
		Expires:      (time.Now().Unix() + constant.JWTAccessTime) * 1000,
	}
	return
}

// VerifyCode 检查验证码是否合法
func (ser userService) VerifyCode(ver model.VeryCode) bool {
	return true
}

func (ser userService) AddUser(arg model.AddUser) (err error) {
	u := model.User{
		UserId:    utils.GetSoftId(),
		Username:  arg.Username,
		Password:  arg.Password,
		Status:    model.UserStatusActivated,
		IsOnline:  model.UserOffline,
		AccountLv: model.AccountLvForUser,
		Creator:   "",
		CreatorId: model.RootId,
		CreatedAt: time.Now().Unix(),
		UpdatedAt: 0,
		DeletedAt: 0,
	}
	return repository.UserRepository.AddUser(u)
}
